#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
import wx.grid
import threading
import xfLib.media as media
from xfLib.services import BaiduTTS,GoogleTTS, MsImageSearch
from xfLib.net import SimpleDownLoader,DL
from xfLib.dao import WordsDao

class GridTable(wx.grid.PyGridTableBase):
    def __init__(self,data):
        wx.grid.PyGridTableBase.__init__(self)
        self.colLabels = ["ID", u"英文", u"中文"]  
        self.data=data

    def GetNumberRows(self):
        return len(self.data)

    def GetNumberCols(self):
        return 3

    def IsEmptyCell(self, row, col):
        return self.data[row][col] is not None

    def GetValue(self, row, col):
        return self.data[row][col]

    def SetValue(self, row, col, value):
        pass
        
    def GetColLabelValue(self, col):#列标签
        return self.colLabels[col]
       
    def GetRowLabelValue(self, row):#行标签
        pass
       


"""
事件处理
"""

class App(wx.App):
    
    def __init__(self):
        wx.App.__init__(self,False)
        
    def OnInit(self):
        self.frmMain=MainFrame()
        self.frmMain.Center()
        self.frmMain.Show()
        return True
    
    def OnExit(self):
        pass
        
class ImageView(wx.Panel):
    def __init__(self,parent,tag,size=(150,150)):
        wx.Panel.__init__(self,parent)
        self.size=size
        self.tag=tag 
        self.used=False   
        self.InitUI()
        
    def InitUI(self):
        """
        在 Panel 中加入 StaticBitmap
        """
        w,h=self.size
        self.sb=wx.StaticBitmap(self,bitmap=wx.EmptyBitmap(w,h))
        self.sb.Bind(wx.EVT_LEFT_DOWN,self.OnClick)
        sizer=wx.GridSizer()
        sizer.Add(self.sb,0,wx.ALIGN_CENTER|wx.EXPAND|wx.ALL,4)
        self.SetSizer(sizer)
        self.Fit()
        
    def SetImage(self,stream):
        w,h=self.size
        if(wx.Image.CanReadStream(stream)):
            image = wx.ImageFromStream(stream)
            self.sb.SetBitmap(wx.BitmapFromImage(image.Scale(w,h)))
            self.Refresh() 
            self.used=True      
 
    def Clear(self):
        w,h=self.size
        self.SetBackgroundColour(wx.BLACK)
        self.sb.SetBitmap(wx.EmptyBitmap(w,h))
        self.Refresh()
        self.used=False   
        
    def GetEmptyBitmap(self,color=wx.WHITE):
        bmp=wx.EmptyBitmap(150,150)
        dc=wx.MemoryDC(bmp)
        dc.SetBackground(wx.Brush(color))
        dc.Clear()
        dc.SelectObject(wx.NullBitmap)
        return bmp
        
    def OnClick(self,event):
        if(self.used):
            self.Parent.OnClick(self.tag)
        
    def Select(self):
        self.SetBackgroundColour(wx.RED)
        self.Refresh()
        
    def UnSelect(self):
        self.SetBackgroundColour(wx.NullColor)
        self.Refresh()
        

        
class ImageViewList(wx.Panel):
    def __init__(self,parent):
        wx.Panel.__init__(self,parent)
        self.image_list=[]
        self.seleted_id=0
        self.count=0
        self.InitUI()
        
    def InitUI(self,length=32):
        self.SetBackgroundColour(wx.WHITE)
        sizer=wx.GridSizer(3,6,2,2)
        for i in range(0,length):
            iv=ImageView(self,i)
            sizer.Add(iv,0,wx.ALIGN_CENTER|wx.EXPAND|wx.ALL,1)
            self.image_list.append(iv)
            
        self.SetSizer(sizer)
        self.Fit()
        
            
    def Clear(self):
        for iv in self.image_list:
            iv.Clear()
        self.seleted_id=0
        self.count=0

    def OnClick(self,tag):
        iv=self.image_list[self.seleted_id]
        iv.UnSelect()
        iv=self.image_list[tag]
        iv.Select()
        self.seleted_id=tag
        print tag

    def GetImage(self):
        return self.image_list[self.seleted_id]
        
    def SetImage(self,stream):
        if(self.count<17):
            self.image_list[self.count].SetImage(stream)
            self.count=self.count+1
            
                
                
class FrameMain(wx.Frame):
    
    def __init__(self):
        wx.Frame.__init__(self,parent=None,id=wx.ID_ANY,title=u"儿童英语",size=(800,600))
        self.dao=WordsDao()
        self.__Layout()

        
        
    def __Layout(self):
        #创建各种控件
        panel=wx.Panel(self)

        bsLeft = wx.BoxSizer( wx.VERTICAL )
        #加入网格
        bsLeft.Add(self.__CreateGrid(panel), 0, wx.ALL|wx.EXPAND, 5 ) 
        #加入图像框    
        bsLeft.Add(self.__CreateStaticBitmap(panel), 0, wx.ALIGN_CENTER, 5 )
        
        
        bsBottom = wx.BoxSizer( wx.HORIZONTAL )
        #加入左边
        bsBottom.Add( bsLeft, 0, wx.EXPAND, 5 )
        #加入右边 GridView
        bsBottom.Add( self.__CreateImageList(panel), 1, wx.EXPAND |wx.ALL, 5 )
        
        bsParent = wx.BoxSizer( wx.VERTICAL )
        #加入输入框区域
        bsParent.Add( self.__CreateTopArea(panel), 0, wx.EXPAND, 5 )
        #加入下边
        bsParent.Add( bsBottom, 0, wx.EXPAND, 5 )
            
        panel.SetSizer( bsParent )
        panel.Layout()    
        
        
    def __CreateTopArea(self,parent):
        """
        #创建顶部搜索部分---------------------------------
        """
        panel=wx.Panel(parent)
        sizer = wx.BoxSizer(wx.HORIZONTAL )
        self.txtEn=wx.TextCtrl(panel)
        self.txtZh=wx.TextCtrl(panel)
        self.btnSearch = wx.Button(panel,-1,u'搜索')
        self.btnSave = wx.Button(panel,-1,u'保存')
        self.Bind(wx.EVT_BUTTON,self.OnSearch,self.btnSearch)
        self.Bind(wx.EVT_BUTTON,self.OnSaveClick,self.btnSave)
        
        sizer.AddMany([
                       ((12, 0), 0, wx.EXPAND, 5 ),
                       (wx.StaticText(panel,-1,u'英文：'),0,wx.ALIGN_CENTER|wx.ALL, 5 ,10 ),
                       (self.txtEn,0,wx.ALL, 5),
                       ((12, 0), 0, wx.EXPAND, 5 ),
                       (wx.StaticText(panel,-1,u'中文：'),0,wx.ALIGN_CENTER|wx.ALL, 5),
                       (self.txtZh,0,wx.ALL, 5),
                       ((12, 0), 0, wx.EXPAND, 5 ),
                       (self.btnSearch,0,wx.ALL, 5),
                       ((12, 0), 0, wx.EXPAND, 5 ),
                       (self.btnSave,0,wx.ALL, 5)                   
                ])
        panel.SetSizer(sizer)
        return panel
        
    def __CreateGrid(self,parent):
        """
        #创建网格---------------------------------
        """
        grid = wx.grid.Grid(parent)
        table = GridTable(self.dao.load())
        grid.SetTable(table, True)
        
        grid.EnableEditing(False)
        grid.DisableDragColSize()
        grid.DisableDragRowSize()
        grid.DisableDragGridSize()
        grid.SetRowLabelSize(0)
        grid.AutoSizeColumns()
        grid.SetSelectionMode(wx.grid.Grid.wxGridSelectRows)
        grid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK,self.OnGridClick)
        self.grid=grid
        return self.grid
        
    def __CreateStaticBitmap(self,parent):
        """
        #创建图像框---------------------------------
        """
        img=wx.Image(u"none.jpg")
        self.bmpSelected = wx.StaticBitmap(parent, bitmap=wx.BitmapFromImage(img.Scale(120,120)))
        return self.bmpSelected
        
    def __CreateImageList(self,parent):
        """
        #创建 ListView---------------------------------
        """
        self.ivlist=ImageViewList(parent)
        return self.ivlist

        
    def OnSearch(self,event):
        print 'search.......'
        ThreadImageFetch(self).start()
        
        
    def OnSaveClick(self,event):
        ThreadTTSFetch(self).start()
        
        
    def OnGridClick(self,event):
        print event.GetRow()
        event.Skip()
        
  
class ThreadImageFetch(threading.Thread):
    
    def __init__(self,win):
        threading.Thread.__init__(self)
        self.win=win
        
    def run(self):
        txt_en=self.win.txtEn.GetValue().strip().capitalize()
        msis=MsImageSearch(txt_en)
        li=[]
        li.extend(msis.request())
        li.extend(msis.request())
        li.extend(msis.request())
        li.extend(msis.request())
        li.extend(msis.request())
        li.extend(msis.request())
        li.extend(msis.request())
        li.extend(msis.request())
        print li
        for url in li:
            ThreadDownLoader(self.win,url).start()
            
class ThreadDownLoader(threading.Thread):
    
    def __init__(self,win,url):
        threading.Thread.__init__(self)
        self.win=win
        self.url=url
        
    def run(self):
        dl=SimpleDownLoader(self.url)
        stream=dl.open()
        if stream:
            wx.CallAfter(self.win.ivlist.SetImage,stream)
        
        
class ThreadTTSFetch(threading.Thread):
    
    def __init__(self,win):
        threading.Thread.__init__(self)
        self.win=win
    
    def run(self):
        txt_en=self.win.txtEn.GetValue().strip().capitalize()
        txt_zh=self.win.txtZh.GetValue().strip()
        
        tts_en=None
        tts_zh=None
        
        if(len(txt_en)>0):
            tts=BaiduTTS()
            tts_en=tts.request(txt_en.lower())
            media.speak(tts_en)
        
        if(isinstance(txt_zh,unicode)):
            temp=txt_zh.encode("utf-8")
        if(len(temp)>0):
            tts=GoogleTTS()
            tts_zh=tts.request('zh_CN',temp)
            media.speak(tts_zh)
        
        data={
              'txt_en':txt_en,
              'txt_zh':txt_zh,
              'tts_en':tts_en,
              'tts_zh':tts_zh,
              'image':None}
        
        
if __name__=='__main__':
    #初始化程序
    app=wx.App(False)
    frm=FrameMain()
    frm.Center()
    frm.Show()
    #开始消息循环
    app.MainLoop()
    